package controllers

import (
	"github.com/astaxie/beego"
	"shuxianghui/models"
	"HTshuxianghui/htmodels"
	"strconv"
	"time"
	"os"
	"strings"
	"github.com/astaxie/beego/validation"
)

type HomeController struct {
	beego.Controller
}

//带了参数导致bootstrap table无法正常使用
func (c *HomeController)HTHomeList_html() {
	c.TplName = "home_list.html"
	c.Render()
}

func (c *HomeController)HTHomeList() {
	limit, _ := c.GetInt("limit")
	offset, _ := c.GetInt64("offset")
	orderby := ""
	if order := c.GetString("order"); order != "asc" {
		orderby += "-"
	}
	orderfiled := c.GetString("sort")
	orderby += orderfiled
	if orderfiled == "" {
		orderby = "-Id"
	}
	orderby="-EditTime"
	search := c.GetString("search")
	fileds := []string{ "Id", "ManageType", "PicPath", "PicHref"}
	Home := []models.Home{}
	htmodels.HTHomeGetList(&Home, fileds,  offset, limit, search, "Id", orderby)
	count, _ := htmodels.HTHomeGetCount(search, "Id", )
	c.Data["json"] = map[string]interface{}{"rows":&Home, "total":count}
	c.ServeJSON()
}


func (c *HomeController)HTHomeDetail() {
	Id, _ := c.GetInt64("Id")
	if Id != 0 {
		c.Data["update"] = true
		SetHomeDetailInfo(c, Id)
	}
	mytype,_:=c.GetInt("type")
	c.Data["Type"]=mytype
	c.TplName = "home_detail.html"
}

func SetHomeDetailInfo(c *HomeController, Id int64) {
	Home := models.Home{Id:int(Id)}
	htmodels.HTHomeGetDetail(&Home)
	c.Data["Home"] = &Home
}

func (c *HomeController)HTHomeAdd() {
	Home := models.Home{}
	if err := c.ParseForm(&Home); err != nil {
		Message(&c.Controller, "", "输入数据不对,即将返回！" + err.Error(), "", true)
	}
	Home.EditTime=time.Now()
	valide := validation.Validation{}
	if b, err := valide.Valid(&Home); !b || err != nil {
		if !b {
			Message(&c.Controller, "", "数据验证失败，即将返回！", "", true)
		}
		if err != nil {
			Message(&c.Controller, "", "数据验证错误，即将返回！" + err.Error(), "", true)
		}
	}
	if err := htmodels.HTHomeAdd(&Home); err != nil {
		Message(&c.Controller, "", "添加失败，即将返回！" + err.Error(), "", true)
	}
	path:="/var/uploads/shuxianghui"
	url:= "uploads/Home/PicPath"
	if strings.Index(url, "?") != -1 {
		url = url[:strings.Index(url, "?")]
	}
	totalpath := path + url[strings.Index(url, "uploads") + len("uploads"):]
	GenerateTumbnail(totalpath, "Home", int64(Home.Id), 100, 100)
	Message(&c.Controller, `/home/detail`, "添加成功！", "", false)
}


func (c *HomeController)HTHomeUpdate() {
	Id , _ := c.GetInt64("Id");
	Home := models.Home{Id:int(Id)}
	if err:=htmodels.HTHomeGetDetail(&Home);err!=nil{
		Message(&c.Controller, "", "严重错误，请联系管理员,即将返回！" + err.Error(), "", true)
	}
	if err := c.ParseForm(&Home); err != nil {
		Message(&c.Controller, "", "输入数据不对,即将返回！" + err.Error(), "", true)
	}
	valide := validation.Validation{}
	if b, err := valide.Valid(&Home); !b || err != nil {
		if !b {
			Message(&c.Controller, "", "数据验证失败，即将返回！", "", true)
		}
		if err != nil {
			Message(&c.Controller, "", "数据验证错误，即将返回！" + err.Error(), "", true)
		}
	}
	Home.EditTime=time.Now()
	if err := htmodels.HTHomeUpdate(&Home); err != nil {
		Message(&c.Controller, "", "更新失败，即将返回！" + err.Error(), "", true)
	}
	Message(&c.Controller, `/home/list_html`, "更新成功！", "", false)
}


func (c *HomeController)HTHomeDelete() {
	Ids := make([]int64, 0, 100)
	c.Ctx.Input.Bind(&Ids, "Id")
	count, err := htmodels.HTHomeDelete(Ids)
	if err != nil {
		Json_Message(&c.Controller, 0, "删除失败" + err.Error())
	}
	Json_Message(&c.Controller, 1, "删除" + strconv.FormatInt(count, 10) + "行")
}


//image upload
func (c *HomeController)HTHomePicUp() {
	Id, _ := c.GetInt64("Id")
	_, h, err := c.GetFile("Filedata")
	if err != nil {
		Json_Message(&c.Controller, 1, "file upload error")
	}
	url := c.GetString("imagepath")
	totalpath := ""
	path := beego.AppConfig.String("uploadspath")
	//if url == "" {
	//	typename := h.Filename[strings.LastIndex(h.Filename, "."):]
	//	date := time.Now().Format("2006-01-02")
	//	directory := "/home/pics/" + date
	//	filename := RandString(8)
	//	totalpath = path + directory + "/" + filename + typename
	//	url = "/uploads" + directory + "/" + filename + typename
	//	os.MkdirAll(path + directory, 0777)
	//} else {
	//	if strings.Index(url, "?") != -1 {
	//		url = url[:strings.Index(url, "?")]
	//	}
	//	totalpath = path + url[strings.Index(url, "uploads") + len("uploads"):]
	//}
	typename := h.Filename[strings.LastIndex(h.Filename, "."):]
	date := time.Now().Format("2006-01-02")
	directory := "/home/pics/" + date
	filename := RandString(8)
	totalpath = path + directory + "/" + filename + typename
	url = "/uploads" + directory + "/" + filename + typename
	os.MkdirAll(path + directory, 0777)

	if err := c.SaveToFile("Filedata", totalpath); err != nil {
		Json_Message(&c.Controller, 1, "file save error" + err.Error())
	}
	if Id != 0 {
		GenerateTumbnail(totalpath, "Home", Id, 100, 100)
	}
	Json_Message(&c.Controller, 0, url + "?time=" + time.Now().String())
}

